import 'package:hi_common/util/logger.dart';

import 'BarrageModel.dart';
import 'package:flutter/cupertino.dart';
import 'package:web_socket_channel/io.dart';

abstract class ISocket {
  /// 和服务器建立连接
  ISocket open(String vid);

  /// 发送弹幕
  ISocket send(String message);

  /// 关闭链接
  void close();

  /// 接收弹幕
  ISocket listen(ValueChanged<List<BarrageModel>> callback);
}

class HiSocket implements ISocket {
  static const _URL = 'wss://api.devio.org/uapi/fa/barrage/';
  IOWebSocketChannel? _channel;
  ValueChanged<List<BarrageModel>>? _callBack;
  Map<String, dynamic> headers;

  HiSocket(this.headers);

  @override
  void close() {
    _channel?.sink.close();
  }

  @override
  ISocket listen(ValueChanged<List<BarrageModel>> callback) {
    _callBack = callback;
    return this;
  }

  @override
  ISocket open(String vid) {
    _channel = IOWebSocketChannel.connect(_URL + vid,
        headers: headers, pingInterval: const Duration(seconds: 50));

    _channel?.stream.handleError((error) {
      logger.i("链接发生错误:$error");
    }).listen((message) {
      _handleMessage(message);
    });

    return this;
  }

  @override
  ISocket send(String message) {
    _channel?.sink.add(message);
    return this;
  }

  void _handleMessage(message) {
    logger.i(message);
    var result = BarrageModel.fromJsonString(message);
    _callBack?.call(result);
  }
}
